package com.botao.cms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.botao.cms.CMSApplication;
import com.botao.cms.pojo.FileLocation;
import com.botao.cms.service.FileLocationService;
import com.botao.cms.utils.AjaxResult;
import com.botao.cms.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Slf4j
@Controller
public class DownLoadController {
    @Autowired
    FileLocationService fileLocationService;


    @RequestMapping("admin/download/list")
    public String list() {
        return "admin/download/list";
    }

    @ResponseBody
    @RequestMapping("admin/download/file/list")
    public AjaxResult fileList() {
        return AjaxResult.success(fileLocationService.list(new QueryWrapper<FileLocation>().select("id", "file_name")));
    }

    @ResponseBody
    @RequestMapping("admin/downloadFileById/{id}")
    public void downloadFile(@PathVariable String id, HttpServletResponse response) throws IOException {

        FileLocation fileLocation = fileLocationService.getById(id);
        String suffix = fileLocation.getFileLocation().substring(fileLocation.getFileLocation().lastIndexOf("."));
        String fileName = new String((fileLocation.getFileName() + suffix).getBytes(StandardCharsets.UTF_8));
        log.info("附件名称{}", fileName);
        String path = new ApplicationHome(CMSApplication.class).getDir().getPath();
        String location = path + "/file/" + fileLocation.getFileLocation();
        log.info(location);
        FileInputStream fis = new FileInputStream(new File(location));
        BufferedInputStream bis = new BufferedInputStream(fis);

        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);

        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        response.setContentType("application/octet-stream;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        bos.close();
        os.close();
        bis.close();
        os.close();
    }
    @RequestMapping("admin/sys/download/file_upload")
    public String uploadPage() {
        return "admin/sys/file_upload";
    }

    @ResponseBody
    @RequestMapping("admin/sys/download/file/upload")
    public AjaxResult upload(MultipartFile file, String name) throws IOException {
        if (file.isEmpty()) {
            return AjaxResult.error(500, "文件为空");
        }
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        int i = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(i);
        String fileName = UUID.randomUUID().toString().replace("-", "").concat(suffix);
        String uploadPath = new ApplicationHome(CMSApplication.class).getDir().getPath() + "/file/";
        log.info("文件存放地址{}", uploadPath);
        File uploadFileDir = new File(uploadPath);
        if (!uploadFileDir.exists()) {
            uploadFileDir.mkdirs();
        }
        File uploadFile = new File(uploadFileDir, fileName);
        log.info("文件前端名称{}", name);
        log.info("文件名称{}", fileName);
        log.info("文件对象{}", uploadFile);
        file.transferTo(uploadFile);
        boolean save = fileLocationService.save(new FileLocation(UUIDUtil.getuuid(), name, fileName, 0));
        return AjaxResult.success(save);
    }
}
